<template>
  <div style="margin-left: 10px">
    <div style="margin-top: 10px">
      点检编号：<el-input style="width: 20%"></el-input> 负责人：<el-input
        style="width: 20%"
      ></el-input>
      配件名称：<el-input style="width: 20%"></el-input>
      &nbsp;
      <el-button @click="getEquipmentList">查询</el-button>
    </div>
    <el-button
      @click="createModel"
      type="success"
      style="margin-top: 10px; margin-left: 90%; margin-bottom: 10px"
      >创建模板</el-button
    >
    <el-table :data="contentTable" border>
      <el-table-column prop="contentName" label="点检内容"></el-table-column>
      <el-table-column prop="department" label="部门"></el-table-column>
      <el-table-column prop="updateTime" label="最后更新时间"></el-table-column>
      <el-table-column prop="remarks" label="备注信息"></el-table-column>
      <el-table-column label="启用状态">
        <template #default="scope">
          <el-tag v-if="scope.ststus == 1" type="success">启用状态</el-tag>
          <el-tag v-else type="danger">停用状态</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="success" @click="showMessage(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageForm.pageNum"
      v-model:page-size="pageForm.pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="1"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog v-model="createDiavissable" title="创建模板" draggable overflow>
      <el-form>
        <el-form-item label="标题名称:"
          ><el-input v-model="CreateForm.contentName"></el-input
        ></el-form-item>
        <el-form-item label="检修部门:">
          <el-tree-select
            v-model="CreateForm.deptId"
            :data="deptOptions"
            check-strictly
            :render-after-expand="false"
            show-checkbox
            check-on-click-node
            style="width: 240px"
            @change="handleValueChange"
          />
        </el-form-item>
        <el-form-item label="备注信息:"
          ><el-input v-model="CreateForm.remarks"></el-input
        ></el-form-item>
      </el-form>
      <el-button @click="addInsForm('text')" type="primary"
        >添加文本框</el-button
      >
      <el-button @click="addInsForm('select')" type="success"
        >添加单选框</el-button
      >
      <el-button @click="addInsForm('muilsel')" type="warning"
        >添加多选框</el-button
      >
      <el-button @click="addInsForm('number')" type="danger"
        >添加数字</el-button
      >

      <el-scrollbar ref="scrollbarRef" height="400px">
        <el-form :model="CreateForm.detail" ref="formRef">
          <el-form-item v-for="(item, index) in CreateForm.detail" :key="index">
            <div
              v-if="item.boxType == 1"
              style="
                display: flex;
                flex-wrap: wrap;
                width: 100%;
                height: auto;
                border: 1px solid #409eff;
                margin-top: 10px;
              "
            >
              <el-divider content-position="center" style="margin-top: -2px"
                >文本框</el-divider
              >
              <span style="margin-bottom: 20px; margin-left: 10px"
                >标题名称：</span
              >
              <el-input
                style="width: 70%; height: 30px"
                v-model="item.pointCheckName"
              ></el-input
              ><el-button
                type="danger"
                @click="remove(index)"
                style="margin-left: 20px"
                >移除</el-button
              >
            </div>
            <div
              v-if="item.boxType == 2"
              style="
                display: flex;
                flex-wrap: wrap;
                width: 100%;
                height: auto;
                border: 1px solid #67c23a;
                margin-top: 10px;
              "
            >
              <el-divider content-position="center" style="margin-top: -2px"
                >选择组件</el-divider
              >
              <span style="margin-left: 10px">选项名称：</span
              ><el-input
                style="width: 60%; height: 30px"
                v-model="item.pointCheckName"
              ></el-input>
              <el-button
                type="danger"
                @click="remove(index)"
                style="margin-left: 20px"
                >移除</el-button
              >
              <el-button
                type="danger"
                @click="addOptions('sel', index)"
                style="margin-left: 20px"
                >添加选项</el-button
              >
              <div style="width: 100%">
                <el-checkbox-group
                  v-model="item.checkedCities"
                  :max="1"
                  @change="consoleCities(index, item.checkedCities)"
                >
                  <el-checkbox
                    v-for="option in item.optionContent"
                    :key="option.value"
                    :label="option.label"
                    size="large"
                    style="margin-left: 100px"
                  >
                    <span
                      v-if="!isEditing(option)"
                      @dblclick="editLabel(option)"
                      >{{ option.label }}</span
                    >
                    <input
                      v-else
                      type="text"
                      :value="option.label"
                      @input="updateLabel($event, option)"
                      @blur="doneEditing(option)"
                      @keyup.enter="doneEditing(option)"
                    />
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
            <div
              v-if="item.boxType == 3"
              style="
                display: flex;
                flex-wrap: wrap;
                width: 100%;
                height: auto;
                border: 1px solid #e6a23c;
                margin-top: 10px;
              "
            >
              <el-divider content-position="center" style="margin-top: -2px"
                >多选组件</el-divider
              >
              <span>选项名称：</span
              ><el-input
                style="width: 60%; height: 30px"
                v-model="item.pointCheckName"
              ></el-input>
              <el-button
                type="danger"
                @click="remove(index)"
                style="margin-left: 20px"
                >移除</el-button
              >
              <el-button
                type="danger"
                @click="addOptions('sel', index)"
                style="margin-left: 20px"
                >添加选项</el-button
              >
              <div style="width: 100%">
                <el-checkbox-group v-model="item.checkedCities">
                  <el-checkbox
                    v-for="option in item.optionContent"
                    :key="option.value"
                    v-model="option.value"
                    :label="option.label"
                    size="large"
                    style="margin-left: 100px"
                  >
                    <span
                      v-if="!isEditing(option)"
                      @dblclick="editLabel(option)"
                      >{{ option.label }}</span
                    >
                    <input
                      v-else
                      type="text"
                      :value="option.label"
                      @input="updateLabel($event, option)"
                      @blur="doneEditing(option)"
                      @keyup.enter="doneEditing(option)"
                    />
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
            <div
              v-if="item.boxType == 4"
              style="
                display: flex;
                flex-wrap: wrap;
                width: 100%;
                height: auto;
                border: 1px solid #f89898;
                margin-top: 10px;
              "
            >
              <el-divider content-position="center" style="margin-top: -2px"
                >数字组件</el-divider
              >
              <span style="margin-left: 10px; margin-bottom: 20px"
                >选项名称：</span
              ><el-input
                style="width: 60%; height: 30px"
                v-model="item.pointCheckName"
              ></el-input>
              <el-button
                type="danger"
                @click="remove(index)"
                style="margin-left: 20px"
                >移除</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <el-button @click="surnSumbitForm">确定</el-button>
        <el-button @click="previewDiavissable = true">预览</el-button>
      </template>
      <!-- //预览框 -->
      <el-dialog v-model="previewDiavissable">
        <el-form>
          <el-form-item v-for="(item, index) in CreateForm.detail" :key="index">
            <div v-if="item.boxType == 1" style="display: flex">
              <span>{{ item.pointCheckName }}:</span><el-input></el-input>
            </div>
            <div v-if="item.boxType == 2" style="display: flex">
              <span>{{ item.pointCheckName }}:</span>
              <el-checkbox-group v-model="item.checkedCities">
                <el-checkbox
                  v-for="(city, index) in item.optionContent"
                  :key="index"
                  :label="city.label"
                  :value="city.label"
                >
                  {{ city.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { addContent, addDianjian, getDjDept } from '@/api/baseUrl12'
import { ElMessage } from 'element-plus'
const consoleCities = (index) => {
  CreateForm.value.detail[index].checkedCities = ['选项值1']
  console.log(CreateForm.value.detail[index].checkedCities)
}

const isEditing = (option) => {
  return option.isEditing
}

const editLabel = (option) => {
  option.isEditing = true
}

const updateLabel = (event, option) => {
  option.label = event.target.value
}

const doneEditing = (option) => {
  option.isEditing = false
}
const contentTable = ref()
// 获取内容
const addContentTable = async () => {
  const res = await addContent()
  contentTable.value = res.rows
}
// 分页
const pageForm = ref({
  pageSize: '',
  pageNum: ''
})

const size = ref('default')
const handleSizeChange = (val) => {
  pageForm.value.pageSize = val
  pageForm.value.pageNum = '1'
  addContentTable(pageForm.value)
}
const handleCurrentChange = (val) => {
  pageForm.value.pageNum = val
  addContentTable(pageForm.value)
}
const showMessage = (row) => {
  ElMessage({
    message: row,
    type: 'succes'
  })
}
// 创建模板
const createDiavissable = ref(false)
const createModel = () => {
  createDiavissable.value = true
}
const CreateForm = ref({
  contentName: '',

  deptName: '',
  remarks: '',

  detail: []
})
const scrollbarRef = ref(null)
// 拿表单的元素高度
const formRef = ref(null)
const addOptions = (type, index) => {
  //   if (type == 'sel') {
  //     const temp = { label: '选项值1' }
  //     console.log(CreateForm.value.detail[index])
  //     CreateForm.value.detail[index].optionContent.push(temp)
  //   }
  // }
  let optionCount = 1 // 初始化计数器

  // 检查 CreateForm 是否已经有一个计数器，如果有，则使用它
  if (CreateForm.value.detail[index].optionCount) {
    optionCount = CreateForm.value.detail[index].optionCount + 1
  }

  if (type == 'sel') {
    const temp = { label: `选项值${optionCount + 2}` }
    CreateForm.value.detail[index].optionContent.push(temp)
    // 更新计数器
    CreateForm.value.detail[index].optionCount = optionCount
  }
}
const addInsForm = (type) => {
  if (type == 'text') {
    const temp = ref({
      pointCheckName: '',

      optionContent: {},

      boxType: 1
    })
    CreateForm.value.detail.push(temp.value)
    console.log(CreateForm.value)
  }
  if (type == 'select') {
    const temp = ref({
      pointCheckName: '',

      optionContent: [{ label: '选项值1' }, { label: '选项值2' }],
      checkedCities: [],

      boxType: 2
    })
    CreateForm.value.detail.push(temp.value)
  }
  if (type == 'muilsel') {
    const temp = ref({
      pointCheckName: '',

      optionContent: [{ label: '选项值1' }, { label: '选项值2' }],
      checkedCities: [],

      boxType: 3
    })
    CreateForm.value.detail.push(temp.value)
  }
  if (type == 'number') {
    const temp = ref({
      pointCheckName: '',

      optionContent: { min: '', max: '', decimals: '', rangeType: '' },

      boxType: 4
    })
    CreateForm.value.detail.push(temp.value)
  }
  nextTick(() => {
    // 滚动到底部
    scrollbarRef.value.scrollTo({
      left: 0,
      top: formRef.value.$el.clientHeight
    })
  })
}

const remove = (index) => {
  //移除项
  CreateForm.value.detail.splice(index, 1)
}
const surnSumbitForm = async () => {
  //提交新增加的点检内容
  console.log(CreateForm.value)
  const res = await addDianjian(CreateForm.value)
  console.log(res)
}
// 获取部门
const deptOptions = ref()
const getDjDeptOptions = async () => {
  const res = await getDjDept()
  // 这个地方不要随便换字段
  deptOptions.value = res.data.map((item) => {
    // 创建一个新对象，将 id 的值赋给 value
    return {
      ...item,
      value: item.id,
      // 递归处理 children 属性（如果存在）
      children: item.children
        ? item.children.map((child) => ({
            ...child,
            value: child.id
          }))
        : undefined
    }
  })
}
const handleValueChange = () => {
  const selectedItem = findItemByValue(
    deptOptions.value,
    CreateForm.value.deptId
  )
  if (selectedItem) {
    CreateForm.value.deptName = selectedItem.label
  } else {
    CreateForm.value.deptName = 'Not Found'
  }
}
const previewDiavissable = ref(false)

const findItemByValue = (items, value) => {
  for (const item of items) {
    if (item.value === value) {
      return item
    }
    if (item.children) {
      const childItem = findItemByValue(item.children, value) //递归去比较children的value值
      if (childItem) {
        return childItem
      }
    }
  }
  return null
}

onMounted(() => {
  addContentTable()
  getDjDeptOptions()
})
</script>
<style scoped></style>
